#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
班级管理API路由
"""

from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from datetime import datetime
import json
from models import db, User, Class, Assignment, AssignmentSubmission
from decorators import teacher_required, admin_required

classes_bp = Blueprint('classes', __name__)

@classes_bp.route('/', methods=['GET'])
@jwt_required()
def get_classes():
    """获取班级列表"""
    try:
        current_user_id = int(get_jwt_identity())
        current_user = User.query.get(current_user_id)
        
        if not current_user:
            return jsonify({'error': '用户不存在'}), 404
        
        if current_user.role == 'admin':
            # 管理员可以看到所有班级
            classes = Class.query.filter_by(status='active').all()
        elif current_user.role == 'teacher':
            # 教师只能看到自己管理的班级
            classes = Class.query.filter_by(teacher_id=current_user_id, status='active').all()
        else:
            # 学生只能看到自己所在的班级
            classes = current_user.enrolled_classes
        
        return jsonify({
            'code': 200,
            'message': '获取班级列表成功',
            'data': [cls.to_dict() for cls in classes]
        })
        
    except Exception as e:
        return jsonify({'error': f'获取班级列表失败: {str(e)}'}), 500

@classes_bp.route('/<int:class_id>', methods=['GET'])
@jwt_required()
def get_class_detail(class_id):
    """获取班级详情"""
    try:
        current_user_id = int(get_jwt_identity())
        current_user = User.query.get(current_user_id)
        
        if not current_user:
            return jsonify({'error': '用户不存在'}), 404
        
        class_obj = Class.query.get(class_id)
        if not class_obj:
            return jsonify({'error': '班级不存在'}), 404
        
        # 检查权限
        if current_user.role == 'student':
            if class_obj not in current_user.enrolled_classes:
                return jsonify({'error': '无权访问此班级'}), 403
        elif current_user.role == 'teacher':
            if class_obj.teacher_id != current_user_id:
                return jsonify({'error': '无权访问此班级'}), 403
        
        return jsonify({
            'code': 200,
            'message': '获取班级详情成功',
            'data': class_obj.to_dict_with_students()
        })
        
    except Exception as e:
        return jsonify({'error': f'获取班级详情失败: {str(e)}'}), 500

@classes_bp.route('/', methods=['POST'])
@teacher_required
def create_class():
    """创建班级"""
    try:
        current_user_id = int(get_jwt_identity())
        data = request.get_json()
        
        # 验证必填字段
        if not data.get('name'):
            return jsonify({'error': '班级名称不能为空'}), 400
        
        # 检查班级名称是否已存在
        existing_class = Class.query.filter_by(name=data['name'], teacher_id=current_user_id).first()
        if existing_class:
            return jsonify({'error': '班级名称已存在'}), 400
        
        # 创建班级
        new_class = Class(
            name=data['name'],
            description=data.get('description', ''),
            teacher_id=current_user_id,
            max_students=data.get('max_students', 50),
            status='active'
        )
        
        db.session.add(new_class)
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'message': '创建班级成功',
            'data': new_class.to_dict()
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'创建班级失败: {str(e)}'}), 500

@classes_bp.route('/<int:class_id>', methods=['PUT'])
@teacher_required
def update_class(class_id):
    """更新班级信息"""
    try:
        current_user_id = int(get_jwt_identity())
        data = request.get_json()
        
        class_obj = Class.query.get(class_id)
        if not class_obj:
            return jsonify({'error': '班级不存在'}), 404
        
        # 检查权限
        if class_obj.teacher_id != current_user_id:
            return jsonify({'error': '无权修改此班级'}), 403
        
        # 更新字段
        if 'name' in data:
            # 检查名称是否重复
            existing_class = Class.query.filter_by(name=data['name'], teacher_id=current_user_id).first()
            if existing_class and existing_class.id != class_id:
                return jsonify({'error': '班级名称已存在'}), 400
            class_obj.name = data['name']
        
        if 'description' in data:
            class_obj.description = data['description']
        
        if 'max_students' in data:
            class_obj.max_students = data['max_students']
        
        if 'status' in data:
            class_obj.status = data['status']
        
        class_obj.updated_at = datetime.utcnow()
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'message': '更新班级成功',
            'data': class_obj.to_dict()
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'更新班级失败: {str(e)}'}), 500

@classes_bp.route('/<int:class_id>/students', methods=['POST'])
@teacher_required
def add_student_to_class(class_id):
    """添加学生到班级"""
    try:
        current_user_id = int(get_jwt_identity())
        data = request.get_json()
        
        class_obj = Class.query.get(class_id)
        if not class_obj:
            return jsonify({'error': '班级不存在'}), 404
        
        # 检查权限
        if class_obj.teacher_id != current_user_id:
            return jsonify({'error': '无权管理此班级'}), 403
        
        student_ids = data.get('student_ids', [])
        if not student_ids:
            return jsonify({'error': '学生ID列表不能为空'}), 400
        
        # 检查班级容量
        if len(class_obj.students) + len(student_ids) > class_obj.max_students:
            return jsonify({'error': '班级容量不足'}), 400
        
        added_students = []
        for student_id in student_ids:
            student = User.query.filter_by(id=student_id, role='student').first()
            if not student:
                continue
            
            if student not in class_obj.students:
                class_obj.students.append(student)
                added_students.append(student.to_dict())
        
        db.session.commit()
        
        return jsonify({
            'code': 200,
            'message': f'成功添加 {len(added_students)} 名学生到班级',
            'data': {
                'added_students': added_students,
                'total_students': len(class_obj.students)
            }
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'添加学生失败: {str(e)}'}), 500

@classes_bp.route('/<int:class_id>/students/<int:student_id>', methods=['DELETE'])
@teacher_required
def remove_student_from_class(class_id, student_id):
    """从班级移除学生"""
    try:
        current_user_id = int(get_jwt_identity())
        
        class_obj = Class.query.get(class_id)
        if not class_obj:
            return jsonify({'error': '班级不存在'}), 404
        
        # 检查权限
        if class_obj.teacher_id != current_user_id:
            return jsonify({'error': '无权管理此班级'}), 403
        
        student = User.query.get(student_id)
        if not student:
            return jsonify({'error': '学生不存在'}), 404
        
        if student in class_obj.students:
            class_obj.students.remove(student)
            db.session.commit()
            
            return jsonify({
                'code': 200,
                'message': '成功移除学生',
                'data': {
                    'removed_student': student.to_dict(),
                    'total_students': len(class_obj.students)
                }
            })
        else:
            return jsonify({'error': '学生不在该班级中'}), 400
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': f'移除学生失败: {str(e)}'}), 500

@classes_bp.route('/<int:class_id>/assignments', methods=['GET'])
@jwt_required()
def get_class_assignments(class_id):
    """获取班级作业列表"""
    try:
        current_user_id = int(get_jwt_identity())
        current_user = User.query.get(current_user_id)
        
        if not current_user:
            return jsonify({'error': '用户不存在'}), 404
        
        class_obj = Class.query.get(class_id)
        if not class_obj:
            return jsonify({'error': '班级不存在'}), 404
        
        # 检查权限
        if current_user.role == 'student':
            if class_obj not in current_user.enrolled_classes:
                return jsonify({'error': '无权访问此班级'}), 403
        elif current_user.role == 'teacher':
            if class_obj.teacher_id != current_user_id:
                return jsonify({'error': '无权访问此班级'}), 403
        
        assignments = Assignment.query.filter_by(class_id=class_id).order_by(Assignment.created_at.desc()).all()
        
        return jsonify({
            'code': 200,
            'message': '获取作业列表成功',
            'data': [assignment.to_dict() for assignment in assignments]
        })
        
    except Exception as e:
        return jsonify({'error': f'获取作业列表失败: {str(e)}'}), 500

@classes_bp.route('/<int:class_id>/stats', methods=['GET'])
@teacher_required
def get_class_stats(class_id):
    """获取班级统计信息"""
    try:
        current_user_id = int(get_jwt_identity())
        
        class_obj = Class.query.get(class_id)
        if not class_obj:
            return jsonify({'error': '班级不存在'}), 404
        
        # 检查权限
        if class_obj.teacher_id != current_user_id:
            return jsonify({'error': '无权访问此班级'}), 403
        
        # 获取作业统计
        assignments = Assignment.query.filter_by(class_id=class_id).all()
        total_assignments = len(assignments)
        active_assignments = len([a for a in assignments if a.status == 'active'])
        
        # 获取提交统计
        total_submissions = AssignmentSubmission.query.join(Assignment).filter(Assignment.class_id == class_id).count()
        
        stats = {
            'total_students': len(class_obj.students),
            'total_assignments': total_assignments,
            'active_assignments': active_assignments,
            'total_submissions': total_submissions,
            'average_submission_rate': (total_submissions / (len(class_obj.students) * total_assignments * 100)) if class_obj.students and total_assignments > 0 else 0
        }
        
        return jsonify({
            'code': 200,
            'message': '获取班级统计成功',
            'data': stats
        })
        
    except Exception as e:
        return jsonify({'error': f'获取班级统计失败: {str(e)}'}), 500
